package com.nf.health.app.activity.my;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.my.adapter.MyQuestionExpandableAdapter;
import com.nf.health.app.activity.my.bean.MyHealthyTestCompeteModel;
import com.nf.health.app.activity.my.impl.MyContact;
import com.nf.health.app.core.MyGsonBuilder;
import com.nf.health.app.customview.MyExpandableListView;
import com.nf.health.app.http.Act;
import com.nf.health.app.impl.event.EventContact;
import com.nf.health.app.impl.event.EventType;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.ViewUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 健康明白人知识大赛
 */

public class HousePersionKnowledgeContestActivity extends BaseActivity {
    @Bind(R.id.lv_healthi_compete)
    MyExpandableListView lv_healthi_compete;
    @Bind(R.id.btn_start_compete)
    Button btn_start_compete;
    private MyQuestionExpandableAdapter myQuestionExpandableAdapter;
    private  List<MyHealthyTestCompeteModel.ListBean> list2;
    private Map<String, String> isCheckMap = new HashMap<String, String>();
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_housepersionknowledgecontest);
        ButterKnife.bind(this);
        ViewUtil.setText(this, R.id.titlebar_title_tv, "知识问答");
        initView();
        regisitListener();
        loadData();
    }


    private void loadData() {
        provider.getHealthCompeteListNewQUestion("1","20");
    }
    private void regisitListener() {
        btn_start_compete.setOnClickListener(this);
       /* lv_healthi_compete.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                MyHealthyTestCompeteModel.ListBean listBean = list2.get(groupPosition);
                String keyid = listBean.getId()+"";
                 Map<Integer, String> answerMap = listBean.getHashMap();
                listBean.setSelect(answerMap.get(childPosition));
                isCheckMap.put(keyid, listBean.getSelect());
                myQuestionExpandableAdapter.notifyDataSetChanged();
                return false;
            }
        });*/
        lv_healthi_compete.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                MyHealthyTestCompeteModel.ListBean listBean = list2.get(groupPosition);
                String keyid = listBean.getId()+"";
                Map<Integer, String> answerMap = listBean.getHashMap();
                String currentShowAnswer = answerMap.get(childPosition);
                String selectAnswer = listBean.getSelect();
                StringBuilder answerSb = new StringBuilder();
                if(listBean.getType().equals("1")){//单选
                    if(TextUtils.isEmpty(selectAnswer)){
                        listBean.setSelect(currentShowAnswer);
                    }else {
                        listBean.setSelect(currentShowAnswer);
                    }
                }else if(listBean.getType().equals("2")) {//多选
                    if(TextUtils.isEmpty(selectAnswer)){//之前没有选择答案，则直接添加
                        answerSb.append(currentShowAnswer);
                    }else{//有选择的答案
                        if(selectAnswer.contains(",")){//目前有多个答案
                            String [] selectAnswers = selectAnswer.split(",");
                            List<String>  arrList = Arrays.asList(selectAnswers);
                            List<String>  list = new ArrayList(arrList);
                            if(selectAnswer.contains(currentShowAnswer)){//之前的选择答案包含当前选项
                                list.remove(currentShowAnswer);
                            }else{
                                list.add(currentShowAnswer);
                            }
                            for (int i = 0; i < list.size(); i++) {
                                if(answerSb.length() > 0){
                                    answerSb.append(",").append(list.get(i));
                                }else{
                                    answerSb.append(list.get(i));
                                }
                            }
                        }else{//目前只有一个答案
                            if(!selectAnswer.equals(currentShowAnswer)){//该选项没有选择过
                                answerSb.append(currentShowAnswer);
                                answerSb.append(",").append(selectAnswer);
                            }else {//该选项选择过
                                //不做任何处理
                            }
                        }
                    }
                    listBean.setSelect(answerSb.toString());
                }
                isCheckMap.put(keyid, listBean.getSelect());
                myQuestionExpandableAdapter.notifyDataSetChanged();
                return false;
            }
        });
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        switch (actionName){
            case Act.Flag.FLAG_HOURSE_RESPONSIBLE_GETNEWINQUIRYLIST:
                String flag = JsonUtils.getFiledData(object.toString(),"flag");
                Gson gson = new MyGsonBuilder().createGson();
                if(flag.equals("1")){//问题已经打过，直接跳转到结果界面
                    String answerQuery = JsonUtils.getFiledData(object.toString(), "answer");
                    Bundle bundlePrivacy = new Bundle();
                    bundlePrivacy.putSerializable(MyContact.COMMIT_TO_SENSD_FLAG, answerQuery);
                    ActivityUtils.skipActivity(this, HousePersionCompeteResultActivity.class, bundlePrivacy);
                    EventType eventType = new EventType();
                    eventType.setType( EventContact.FINISH_OPEN__ACTIVITY);
                    EventBus.getDefault().postSticky(eventType);
                }else if(flag.equals("0")){//正常去答题
                    MyHealthyTestCompeteModel myHealthyTestCompeteModel = gson.fromJson(object.toString(), new TypeToken<MyHealthyTestCompeteModel>() {}.getType());
                    if(myHealthyTestCompeteModel != null){
                        try {
                            List<MyHealthyTestCompeteModel.ListBean> list = myHealthyTestCompeteModel.getList();
                            list2 = new MyHealthyTestCompeteModel().parse2(list);
                            if(list2 != null && list2.size() != 0){
                                lv_healthi_compete.setVisibility(View.VISIBLE);
                                btn_start_compete.setVisibility(View.VISIBLE);
                                myQuestionExpandableAdapter = new MyQuestionExpandableAdapter(list2,this);
                                lv_healthi_compete.setAdapter(myQuestionExpandableAdapter);
                                for (int i = 0; i < list.size(); i++) {
                                    lv_healthi_compete.expandGroup(i);
                                }
                            }else{
                                lv_healthi_compete.setVisibility(View.GONE);
                                btn_start_compete.setVisibility(View.GONE);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
    }



    private void initView() {
        lv_healthi_compete.setVisibility(View.GONE);
        btn_start_compete.setVisibility(View.GONE);
        lv_healthi_compete.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.btn_start_compete:
                if(isCheckMap.size() != 0){
                    if(isCheckMap.size() != list2.size()){
                        Set<String> bb = isCheckMap.keySet();//所有题数
                        int questionIndex = 0;
                        for (int i = 0; i <list2.size() ; i++) {
                            questionIndex = i+1;
                            if(!isCheckMap.containsKey(String.valueOf(list2.get(i).getId()))){
                                break;
                            }
                        }
                        showToast("您第"+questionIndex+"题未回答");
                        return;
                    }
                }else{
                    showToast("您还没有答题");
                    return;
                }
                String answer = new MyGsonBuilder().createGson().toJson(isCheckMap);
                Bundle bundlePrivacy = new Bundle();
                bundlePrivacy.putSerializable(MyContact.COMMIT_TO_SENSD_FLAG, answer);
                ActivityUtils.skipActivity(this, HousePersionCompeteResultActivity.class, bundlePrivacy);
                EventType eventType = new EventType();
                eventType.setType( EventContact.FINISH_OPEN__ACTIVITY);
                EventBus.getDefault().postSticky(eventType);
                break;
        }
    }

}
